<template>
  <div class="createPay">
    <div>
      <el-button type="primary" size="mini" @click="newlyAdjustment">{{ $t('btn.save') }}</el-button>
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form :model="subDetails" label-width="100px" size="mini">
          <el-form-item :label="$t('market.billNo')">
            <el-input
              v-model="subDetails.fbillno"
              disabled
            />
          </el-form-item>
          <el-form-item :label="$t('market.billType')">
            <el-select
              v-model="subDetails.fbillTypeId"
              @change="handelTaf"
            >
              <el-option
                v-for="item in billtypes"
                :key="item.fid"
                :label="item.fname"
                :value="item.fid"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.tafName')">
            <el-select v-model="subDetails.ftafId">
              <el-option
                v-for="item in billtypes1"
                :key="item.fid"
                :label="item.fname"
                :value="item.fid"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.comeGounit')">
            <!--  供应商  -->
            <el-autocomplete
              v-if="subDetails.ftafId===1251"
              v-model="subDetails.fsupplierName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch9"
              @focus="handleSupplier"
              @select="supplierSelectRow"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="openSupplier = true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
            <!--            客户-->
            <el-autocomplete
              v-if="subDetails.ftafId===1252"
              v-model.trim="subDetails.fcustName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch"
              @focus="queryTBdCustomerList"
              @select="clientData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="clientVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
            <!--           部门 -->
            <el-input v-if="subDetails.ftafId===1253" v-model="subDetails.fdeptName">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="departVisiblit=true"
              />
            </el-input>
            <!--            员工-->
            <el-input v-if="subDetails.ftafId===1254" v-model="subDetails.fstaffName">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="departRenVisiblit=true"
              />
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('market.businessDate')">
            <el-date-picker
              v-model.trim="subDetails.fdate"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item :label="$t('market.endData')">
            <el-date-picker
              v-model.trim="subDetails.fenddate"
              type="date"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item :label="$t('market.settleCurr')" prop="fsettlecurrId">
            <el-autocomplete
              v-model="subDetails.fcurrencyName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch5"
              @focus="queryTBdCurrency"
              @select="currencySelectRow"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="openCurrency = true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fname }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('market.saler')" prop="fsalerId">
            <el-autocomplete
              v-model="subDetails.fsalerName"
              highlight-first-item
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch3"
              @focus="querySalesperson(1)"
              @select="purchaseData"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="purchaseVisiblit=true"
              />
              <template slot-scope="{ item }">
                <div class="name">{{ item.fuserName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <!--          <el-form-item label="收款组织">-->
          <!--            <el-select v-model.trim="subDetails.orgCol" @change="saleHeadel">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="结算组织">-->
          <!--            <el-select v-model.trim="subDetails.orgSet">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="销售组织">-->
          <!--            <el-select v-model.trim="subDetails.orgSal">-->
          <!--              <el-option-->
          <!--                v-for="option in teamList"-->
          <!--                :key="option.fid"-->
          <!--                :label="option.fname"-->
          <!--                :value="option.fid"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
        </el-form>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.fince')" name="two">
        <el-form :model="subDetails" label-width="100px" size="mini">
          <el-form-item :label="$t('market.exchangeType')">
            <el-input v-model.trim="subDetails.fexchangetype" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.localCurr')">
            <el-input v-model.trim="subDetails.flocalCurr" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.exchangeRate')">
            <el-input v-model.trim="subDetails.fexchangerate" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.shouldamount')">
            <el-input v-model.trim="subDetails.fshouldamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.shouldamount_lc')" label-width="110px">
            <el-input v-model.trim="subDetails.fshouldamountLc" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.realamount')">
            <el-input v-model.trim="subDetails.frealamount" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.realamount_lc')" label-width="110px">
            <el-input v-model.trim="subDetails.frealamountLc" disabled />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="table-content">
      <div style="margin-bottom: 5px;">
        <el-button size="mini" @click="newHang">{{ $t('btn.newHang') }}<!--新增行--></el-button>
        <el-button size="mini" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
        <el-button size="mini" @click="batchFill">{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
      </div>
      <jc-table
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        serial
        @cellClick="cellClick"
        @rowClick="rowClick"
      >
        <!--    结算方式  -->
        <template v-slot:btnState="col">
          <el-select
            v-model="col.scope.row.fpaymenttypeId"
            size="mini"
          >
            <el-option
              v-for="item in paymentDa"
              :key="item.fid"
              :label="item.fname"
              :value="item.fid"
            />
          </el-select>
        </template>
        <!--    付款用途  -->
        <template v-slot:btnStates="col">
          <el-select
            v-model="col.scope.row.freasonId"
            size="mini"
          >
            <el-option
              v-for="item in reasonDa"
              :key="item.fid"
              :label="item.fname"
              :value="item.fid"
            />
          </el-select>
        </template>
        <!--        应付金额-->
        <template v-slot:tagSlot="col">
          <el-input-number
            v-model="col.scope.row.fshouldamount"
            size="mini"
            :min="0"
            @change="handelMount(col.scope.$index)"
          />
        </template>
        <!--        手续费-->
        <template v-slot:billSlot="col">
          <el-input-number
            v-model="col.scope.row.fchargeamount"
            size="mini"
            :min="0"
            @change="handelMount(col.scope.$index)"
          />
        </template>
        <!--        备注-->
        <template v-slot:btnSlot="col">
          <el-input v-model="col.scope.row.fremark" />
        </template>
        <!--       我方银行账号-->
        <template v-slot:orderSlot="col">
          <el-input v-model="col.scope.row.fbankcode">
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="bankShow(col.scope.$index)"
            />
          </el-input>
        </template>
      </jc-table>
    </div>
    <!--币别-->
    <currency v-if="openCurrency" @currency="currencySelectRow" />
    <!--供应商-->
    <supplier v-if="openSupplier" @supplier="supplierSelectRow" />
    <!--客户列表-->
    <client v-if="clientVisiblit" @client="clientData" />
    <!--部门-->
    <responDepart v-if="departVisiblit" @depart="departData" />
    <!--员工-->
    <responRen v-if="departRenVisiblit" @depart="departData1" />
    <!--银行账号-->
    <bank v-if="bankVisiblit" @client="bankData" />
    <!--采购员-->
    <market v-if="purchaseVisiblit" :staff-type="staffType" @market="purchaseData" />
  </div>
</template>

<script>
import {
  createFinReceiptRefundBill
} from '@/api/financial/teller'
import { queryFxxchange, queryOrgDetail, queryRate, queryViewItem } from '@/api/marketManage/marketOrder'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'
import responRen from '@/views/quality/qualityDetail/component/responRen'
import { mapGetters } from 'vuex'
import billFa from '@/views/financial/cashier/mixins'
import bility from '@/mixin/Operability'

export default {
  name: 'CreatePayment',
  components: {
    bank: () => import('@/views/financial/cashier/payment/component/bank'),
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    client: () => import('@/views/market/marketManage/createMarkerOrder/components/client'),
    market: () => import('@/views/market/marketManage/createMarkerOrder/components/market'),
    supplier: () => import('@/views/purchasing/purchase/treePurchasePrice/component/supplier'),
    responDepart: () => import('@/views/quality/qualityDetail/component/responDepart'),
    responRen
  },
  mixins: [autocomplete, billFa, bility],
  data() {
    return {
      paymentDa: [],
      reasonDa: [],
      bankVisiblit: false, // 银行账号
      openSupplier: false, // 供应商弹窗
      clientVisiblit: false, // 客户弹窗
      departVisiblit: false, // 部门弹窗
      departRenVisiblit: false, // 员工弹窗
      openCurrency: false, // 币别、价目表、价格类型
      purchaseVisiblit: false, // 2-采购员(1-销售员)
      staffType: 1, // 销售员
      ftafDa: [],
      subDetails: {
        fdocumentstatus: 'A',
        fbillTypeId: 1257,
        ftafId: 1252,
        fdate: new Date(),
        fenddate: '',
        fsupplierId: '',
        fsettlecurrId: '',
        fshouldamount: 0,
        fshouldamountLc: 0,
        frealamount: 0,
        frealamountLc: 0,
        fcurrencyName: '',
        flocalCurr: ''
      },
      activeName: 'first',
      billtypes: [], // 单据类型
      billtypes1: [], // 单位类型
      indexSelf: 0,
      // 表头
      tableData: [{
        fpaymenttypeId: '', freasonId: '', fshouldamount: 0, fchargeamount: 0, frealamount: 0,
        fbankcode: '', fremark: '', fnumber: '', fname: '', fdescription: '', fpurfbillno: '', salKhddh: ''
      }], // 应付单数据
      tableHeight: '70vh',
      tableHeader: [
        { label: this.$t('market.settleType'), type: 'state', prop: 'fpaymenttypeId', width: '120' },
        { label: this.$t('market.rawReason'), type: 'states', prop: 'freasonId', width: '120' },
        { label: this.$t('market.backAmount'), type: 'tag', prop: 'fshouldamount', width: '80' },
        { label: this.$t('market.chargeamount'), type: 'bill', prop: 'fchargeamount', width: '80' },
        { label: this.$t('market.realBackAmount'), prop: 'frealamount', width: '80' },
        { label: this.$t('market.note'), type: 'btn', prop: 'fremark' },
        { label: this.$t('market.ourBankcode'), type: 'order', prop: 'fbankcode', width: '200' },
        { label: this.$t('market.fmaterial'), prop: 'fnumber', width: '120' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescription', minWidth: '150' },
        { label: this.$t('market.order'), prop: 'fpurfbillno' },
        { label: this.$t('market.paezText1'), prop: 'salKhddh' }
      ]
    }
  },
  computed: {
    ...mapGetters(['fcurrency'])
  },
  created() {
    this.queryTBasBilltype1() // 单位类型
    this.queryTBasBilltype2() // 结算方式ID(SX_SETTLETYPE)
    this.queryTBasBilltype3() // 付款用途ID(SX_PURPOSEPAYMENT)
    this.queryTBasBilltype() // 单据类型
    this.subDetails.flocalCurrId = this.fcurrency.fcurrencyId
    this.subDetails.flocalCurr = this.fcurrency.fcurrencyName
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 280px)' : '73vh'
  },
  methods: {
    // 保存
    newlyAdjustment() {
      const DATA = {
        ...this.subDetails,
        details: this.tableData
      }
      createFinReceiptRefundBill(DATA).then(res => {
        if (res.code === 0) {
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: `/receipyDetail/${res.data.fid}` })
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 计算实付金额
    handelMount(index) {
      const item = this.tableData[index]
      item.frealamount = item.fshouldamount + item.fchargeamount
      this.subDetails.fshouldamount = 0
      this.subDetails.frealamount = 0
      this.tableData.forEach(res => {
        this.subDetails.fshouldamount += res.fshouldamount * 1
        this.subDetails.frealamount += res.frealamount * 1
      })
      const fexchangerate = this.subDetails.fexchangerate
      this.subDetails.fshouldamountLc = (this.subDetails.fshouldamount * fexchangerate).toFixed(2)
      this.subDetails.frealamountLc = (this.subDetails.frealamount * fexchangerate).toFixed(2)
    },
    // 查询汇率
    async querySalerRate() {
      const DATA = {
        tocurrId: this.subDetails.flocalCurrId,
        fromcurrId: this.subDetails.fsettlecurrId,
        queryDate: this.subDetails.fdate
      }
      const { data: RES, code, message } = await queryRate(DATA)
      if (code === 0) {
        this.subDetails.fexchangerate = RES.exchangeRate
        this.subDetails.fexchangetype = RES.exchangeTypeName
        this.subDetails.fexchangetypeId = RES.exchangeTypeId
      } else {
        this.subDetails.fexchangerate = ''
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 银行弹窗
    bankShow(index) {
      this.indexSelf = index
      this.bankVisiblit = true
    },
    bankData(ev) {
      if (ev.fbankaccountId) {
        const item = this.tableData[this.indexSelf]
        item.fbankcodeId = ev.fbankaccountId
        item.fbankcode = ev.faccount
      }
      this.bankVisiblit = false
    },
    // 查询单据类型
    async queryTBasBilltype() {
      const { data: RES } = await queryViewItem({ viewName: 'T_SX_FIN_RECEIPT_REFUND' })
      this.billtypes = RES.list
      this.subDetails.fbillTypeId = RES.list[0].fid
      this.handelTaf(RES.list[0].fid)
    },
    // 查询单位类型
    async queryTBasBilltype1() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_FIN_BAFTYPE' })
      this.billtypes1 = RES.list
    },
    // 查询结算方式
    async queryTBasBilltype2() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_SETTLETYPE' })
      this.paymentDa = RES.list
    },
    // 查询付款用途
    async queryTBasBilltype3() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_RECEIPT_REFUND' })
      this.reasonDa = RES.list
    },
    // 监听数据类型
    handelTaf(val) {
      this.ftafDa = []
      // 单据类型的 fvalue2 值为 单位类型的可选值
      this.billtypes.forEach(res => {
        if (res.fid === val) {
          this.billtypes1.map(res1 => {
            if (res.fvalue2?.split(',').includes(res1.fid + '')) {
              res1.disabled = false
            } else {
              res1.disabled = true
            }
          })
        }
      })
      this.queryProval()
    },
    // 监听单据类型
    queryProval() {
      const DATA = {
        fid: this.subDetails.fbillTypeId || 0,
        viewName: 'T_SX_FIN_RECEIPT_REFUND'
      }
      queryFxxchange(DATA).then(res => {
        if (res.code === 0) {
          this.subDetails = {
            ...this.subDetails,
            orgSet: res.data.fsettleorgid,
            orgCol: res.data.fsettleorgid,
            orgSal: res.data.fsaleorgid,
            fcurrencyName: res.data.fsettleCurr, // 币别
            fsettlecurrId: res.data.fsettleCurrId, // 币别id
            fexchangetype: res.data.fexchangeType, // 汇率类型
            fexchangetypeId: res.data.fexchangeTypeId, // 汇率类型id
            fexchangerate: res.data.fexchangeRate, // 汇率
            ...res.data
          }
        }
      })
    },
    // 监听组织
    saleHeadel(forgids) {
      this.subDetails.orgSal = forgids
      this.subDetails.orgSet = forgids
      queryOrgDetail({ forgids }).then(res => {
        if (res.code === 0) {
          this.subDetails = {
            ...this.subDetails,
            orgSet: res.data.fsettleorgid,
            orgCol: res.data.fsettleorgid,
            orgSal: res.data.fsaleorgid,
            fcurrencyName: res.data.fsettleCurr, // 币别
            fsettlecurrId: res.data.fsettleCurrId, // 币别id
            fexchangetype: res.data.fexchangeType, // 汇率类型
            fexchangetypeId: res.data.fexchangeTypeId, // 汇率类型id
            fexchangerate: res.data.fexchangeRate, // 汇率
            ...res.data
          }
        }
      })
    },
    // 供应商选中
    supplierSelectRow(item) {
      const { fsupplierId, fname } = item
      if (fsupplierId) {
        this.subDetails.fsupplierId = fsupplierId
        this.subDetails.fsupplierName = fname
      }
      this.openSupplier = false
    },
    // 获取客户数据(子传父)
    clientData(item) {
      if (item.fcustId) {
        this.subDetails.fcustId = item.fcustId
        this.subDetails.fcustName = item.fname
      }
      this.clientVisiblit = false
    },
    // 责任部门
    departData(ev) {
      if (ev.fid) {
        this.subDetails.fdeptId = ev.fid
        this.subDetails.fdeptName = ev.fname
      }
      this.departVisiblit = false
    },
    // 员工
    departData1(ev) {
      if (ev.fuserId) {
        this.subDetails.fstaffName = ev.fname
        this.subDetails.fstaffId = ev.fuserId
      }
      this.departRenVisiblit = false
    },
    // 获取销售员
    purchaseData(ev) {
      if (ev.fuserId) {
        this.subDetails.fsalerName = ev.fuserName
        this.subDetails.fsalerId = ev.fuserId
      }
      this.purchaseVisiblit = false
    },
    // 币别选中
    currencySelectRow(item) {
      if (item.fsettleCurrId || item.fcurrencyId) {
        this.subDetails.fsettlecurrId = item.fsettleCurrId || item.fcurrencyId
        this.subDetails.fcurrencyName = item.fsettleCurrIdName || item.fname
        this.querySalerRate()
      }
      this.openCurrency = false
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增行
    newHang() {
      this.tableData.push({
        fpaymenttypeId: '', freasonId: '', fshouldamount: 0, fchargeamount: 0, frealamount: 0,
        fbankcode: '', fremark: '', fnumber: '', fname: '', fdescription: '', fpurfbillno: '', salKhddh: ''
      })
    },
    // 删除行
    delHang() {
      this.tableData.splice(this.indexSelf, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
.tabPosit {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: 3.5vh;
  left: 0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 99999!important;
}
.tabPosit1 {
  padding: 5px;
  box-shadow: 0 0 2px #aaa;
  position: absolute;
  top: -25.69vh;
  left:0;
  background-color: rgba(255, 255, 255, 1);
  z-index: 9999;
}
.createPay {
  @include listBom;
  .header{
    margin-top: 10px;
    .header-name{
      span {
        width: 100px;
        margin-right: 10px;
        text-align: right;
      }
    }
  }
  .el-table{
    &::v-deep .el-input-number .el-input__inner{
      padding: 0;
      width: 75px;
      height: 30px;
    }
    &::v-deep .el-input-number .el-input{
      width: 75px;
      height: 35px;
      line-height: 35px;
    }
    &::v-deep .el-input-number--mini{
      width: 75px;
    }
    &::v-deep .el-input-number__increase{
      display: none;
    }
    &::v-deep .el-input-number__decrease{
      display: none;
    }
    &::v-deep .el-table__footer-wrapper tbody td{
      background: #fdf6ec!important;
    }
  }
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 35px;
      width: 268px;
      margin-bottom: 3px;
      .btnType {
        margin-right: 20px;
      }

      .el-date-editor.el-input {
        width: 100% !important;
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
